package org.example.demo2.handler;


import org.example.demo2.common.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseData<String> handleValidationException(MethodArgumentNotValidException ex){
        StringBuilder errors =new StringBuilder();
        ex.getBindingResult().getFieldErrors().forEach(error->
                errors.append(error.getDefaultMessage()).append(";"));
        return ResponseData.fail(errors.toString());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseData<String> handleException(Exception ex){
        return ResponseData.fail("发生了异常",ex.getMessage());
    }
}
